<!-- 厂家返点管理 -->
<template>
  <div class="app-container">
    <div class="filter-container">
      <div>
        <el-input
          v-model="listQuery.Search"
          placeholder="商品名称/品牌"
          style="width: 200px;"
          class="filter-item"
          clearable
          @clear="handleFilter"
          @keyup.enter.native="handleFilter"
        />
        <el-input
          v-model="listQuery.BarCode"
          placeholder="商品条码"
          style="width: 200px;"
          class="filter-item"
          clearable
          @clear="handleFilter"
          @keyup.enter.native="handleFilter"
        />

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>

        <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="handleAdd">新增返点</el-button>
        <el-button type="warning" icon="el-icon-edit" class="filter-item"
          :disabled="multiSelected.length === 0"
          @click="handleBatchSetRebate"
        >批量设置返点</el-button>
      </div>
    </div>

    <!-- 返点列表 -->
    <el-table v-loading="listLoading" :data="listData.Items"
      row-key="ID"
      style="width: 100%; margin-top: 20px;" border
      @sort-change="handleSortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          {{ scope.row.ID }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品条码" width="150">
        <template slot-scope="scope">
          {{ scope.row.Goods.BarCode }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="商品名称" sortable="custom" prop="GoodsName">
        <template slot-scope="scope">
          {{ scope.row.Goods.Name }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="返点(%)" sortable="custom" prop="Rebate" width="150">
        <template slot-scope="scope"> <!--TODO 没有格式化-->
          {{ (scope.row.Rebate*100).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="生效日期" width="180">
        <template slot-scope="scope">
          {{ scope.row.ValidityStartTime ? scope.row.ValidityStartTime : '未设置' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="结束日期" width="180">
        <template slot-scope="scope">
          {{ scope.row.ValidityEndTime ? scope.row.ValidityEndTime : '长期' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="listData.Total > 0"
      :total="listData.Total"
      :page.sync="listQuery.Page"
      :limit.sync="listQuery.PageSize"
      :page-sizes="[10, 20, 50, 100]"
      @pagination="getListData"
    />

    <!-- 返点设置对话框 -->
    <el-dialog :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :title="dialogType === 'edit' ? '编辑厂家返点' : '新增厂家返点'"
      width="500px"
    >
      <el-form :model="oneData" label-width="100px" label-position="left">
        <el-form-item label="商品条码" prop="BarCode">
          <el-input
            v-model="oneData.BarCode"
            placeholder="请输入13位商品条码"
            maxlength="13"
            :disabled="dialogType === 'edit'"
            @input="handleDialogBarCodeInput"
          />
        </el-form-item>

        <el-form-item v-if="oneData" label="商品信息">
          <div class="selected-goods-info">
            <div>名称: {{ oneData.Name }}</div>
            <div>分类/等级/品牌: {{ oneData.ClassName }}/{{ oneData.LevelName }}/{{ oneData.BrandName }}</div>
            <div>箱规: {{ oneData.BoxRule }}</div>
            <div>厂价: {{ oneData.FactoryPrice }}元</div>
          </div>
        </el-form-item>

        <el-form-item label="返点(%)" prop="Rebate">
          <el-input-number
            v-model="oneData.Rebate"
            placeholder="请输入返点百分比"
            :precision="2"
            :step="0.01"
            :min="0"
            :max="100"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="返点日期">
          <el-row :gutter="12">
            <el-col :span="10">
              <el-date-picker
                v-model="oneData.ValidityStartTime"
                type="month"
                placeholder="开始月份"
                format="yyyy-MM"
                value-format="yyyy-MM"
              />
            </el-col>
            <br>
            <el-col :span="10">
              <el-date-picker
                v-model="oneData.ValidityEndTime"
                type="month"
                placeholder="结束月份"
                format="yyyy-MM"
                value-format="yyyy-MM"
              />
            </el-col>
          </el-row>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            不选择表示"长期有效"
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 批量设置返点弹窗 -->
    <el-dialog title="批量设置返点" :visible.sync="batchSetRebateVisible" width="500px">
      <div style="padding: 20px 0;">
        <div style="margin-bottom: 20px;">
          <span style="font-weight: bold;">已选择 {{ multiSelected.length }} 个商品</span>
        </div>

        <!-- 商品列表，限制高度并添加滚动条 -->
        <div v-if="multiSelected.length > 0" style="max-height: 150px; overflow-y: auto; border: 1px solid #ebeef5; border-radius: 4px; padding: 10px; margin-bottom: 20px; background-color: #fafafa;">
          <div v-for="(item, index) in multiSelected" :key="item.ID" style="padding: 5px 0; border-bottom: 1px solid #eee;" :class="{ 'no-border': index === multiSelected.length - 1 }">
            <span style="margin-right: 10px; font-weight: 500;">{{ item.Goods.BarCode }}</span>
            <span>{{ item.Goods.Name }}</span>
          </div>
        </div>

        <el-form :model="batchRebateData" label-width="100px" label-position="left">
          <el-form-item label="返点(%)" prop="Rebate">
            <el-input-number
              v-model="batchRebateData.Rebate"
              placeholder="请输入返点百分比"
              :precision="2"
              :step="0.01"
              :min="0"
              :max="100"
              style="width: 100%;"
            />
          </el-form-item>

          <el-form-item label="返点日期">
            <el-row :gutter="12">
              <el-col :span="10">
                <el-date-picker
                  v-model="batchRebateData.ValidityStartTime"
                  type="month"
                  placeholder="开始月份"
                  format="yyyy-MM"
                  value-format="yyyy-MM"
                />
              </el-col>
              <br>
              <el-col :span="10">
                <el-date-picker
                  v-model="batchRebateData.ValidityEndTime"
                  type="month"
                  placeholder="结束月份"
                  format="yyyy-MM"
                  value-format="yyyy-MM"
                />
              </el-col>
            </el-row>
            <div style="font-size: 12px; color: #909399; margin-top: 4px;">
              不选择表示"长期有效"
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchSetRebateVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchSetRebate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import * as data_api from '@/api/warehouse/factory_rebate'
import * as goods_api from '@/api/warehouse/goods'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  components: { Pagination },
  data() {
    const defaultData = {
      ID: 0,
      BarCode: '',
      GoodsID: null,
      Rebate: 0,
      ValidityStartTime: '',
      ValidityEndTime: '',
    }

    return {
      oneData: Object.assign({}, defaultData),
      selectedGoods: null,
      listData: {
        Items: [],
        Total: 0
      },
      listLoading: false,
      listQuery: {
        Page: 1,
        PageSize: 10,
        BarCode: '',
        Search: '',
        Sorts: 'updated_at DESC'
      },
      dialogVisible: false,
      dialogType: 'new',
      multiSelected: [], // 批量选中的数据
      batchSetRebateVisible: false,
      batchRebateData: {
        Rebate: 0,
        ValidityStartTime: '',
        ValidityEndTime: ''
      }
    }
  },
  created() {
    this.getListData()
  },
  methods: {
    handleSelectionChange(val) {
      this.multiSelected = val
    },
    handleBatchSetRebate() {
      this.batchRebateData = {
        Rebate: 0,
        ValidityStartTime: '',
        ValidityEndTime: ''
      }
      this.batchSetRebateVisible = true
    },
    async confirmBatchSetRebate() {
      // 验证返点是否在[0.0, 100.0]之间
      const rebate = (this.batchRebateData.Rebate || 0) / 100
      if (rebate < 0.0 || rebate > 1.0) {
        this.$message({
          message: '返点必须在[0%, 100%]之间',
          type: 'warning'
        })
        return
      }

      // 结束时间要么为空 要么不能小于开始时间
      if (this.batchRebateData.ValidityEndTime &&
          this.batchRebateData.ValidityEndTime < this.batchRebateData.ValidityStartTime) {
        this.$message({
          message: '结束时间不能早于开始时间',
          type: 'warning'
        })
        return
      }

      const goodsIds = this.multiSelected.map(item => item.GoodsID)

      try {
        // 使用批量API更新
        await data_api.batch_update({
          GoodsIDs: goodsIds,
          Rebate: rebate,
          ValidityStartTime: this.batchRebateData.ValidityStartTime || null,
          ValidityEndTime: this.batchRebateData.ValidityEndTime || null
        })

        this.$message({
          message: `批量设置返点完成，成功 ${goodsIds.length} 个`,
          type: 'success'
        })

        this.batchSetRebateVisible = false
        this.multiSelected = [] // 清空选择
        this.getListData() // 重新获取列表数据
      } catch (error) {
        this.$message({
          message: '批量设置返点失败',
          type: 'error'
        })
      }
    },
    handleFilter() {
      this.listQuery.Page = 1
      this.getListData()
    },

    async getListData() {
      this.listLoading = true
      try {
        const res = await data_api.list(this.listQuery)
        this.listData = res.data
      } catch (error) {
        this.$message({
          type: 'error',
          message: '获取返点列表失败'
        })
      } finally {
        this.listLoading = false
      }
    },

    handleSortChange({ prop, order }) {
      const sorts = []
      if (prop === 'Rebate') {
        if (order === 'ascending') {
          sorts.push('rebate ASC')
        } else if (order === 'descending') {
          sorts.push('rebate DESC')
        }
        sorts.push('updated_at DESC')
      } else if (prop === 'GoodsName') {
        if (order === 'ascending') {
          sorts.push('g.name ASC')
        } else if (order === 'descending') {
          sorts.push('g.name DESC')
        }
        sorts.push('updated_at DESC')
      }
      this.listQuery.Sorts = sorts.join(', ')
      this.getListData()
    },

    handleAdd() {
      this.dialogType = 'new'
      this.oneData = {
        ID: 0,
        BarCode: '',
        GoodsID: null,
        Rebate: 0,
        RebateDateRange: []
      }
      this.selectedGoods = null
      this.dialogVisible = true
    },

    handleEdit(scope) {
      const rebateInfo = scope.row
      this.dialogType = 'edit'

      console.log(this.oneData)

      // 正确处理日期范围，避免无效值导致的解析错误

      console.log(rebateInfo)
      this.oneData = {
        ID: rebateInfo.ID,
        Name: rebateInfo?.Goods?.Name,
        BarCode: rebateInfo?.Goods?.BarCode || '',
        GoodsID: rebateInfo.GoodsID,
        BoxRule: rebateInfo?.Goods?.BoxRule || '',
        Rebate: (rebateInfo.Rebate || 0.0) * 100, // 返点
        ValidityStartTime: rebateInfo.ValidityStartTime || '',
        ValidityEndTime: rebateInfo.ValidityEndTime || '',
        ClassName: rebateInfo?.Goods?.Category?.ClassName || '',
        LevelName: rebateInfo?.Goods?.Category?.LevelName || '',
        BrandName: rebateInfo?.Goods?.Category?.BrandName || '',
        FactoryPrice: rebateInfo?.Goods?.FactoryPrice || 0.0
      }

      this.dialogVisible = true
    },

    async handleDialogBarCodeInput() {
      if (this.oneData.BarCode.length === 13) {
        await this.searchGoodsByBarCode()
      } else {
        // this.selectedGoods = null
        this.oneData.GoodsID = null
      }
    },

    async searchGoodsByBarCode() {
      try {
        const res = await goods_api.list({
          BarCode: this.oneData.BarCode,
          PageSize: 1
        })

        if (res.data.Items && res.data.Items.length > 0) {
          const goods = res.data.Items[0]
          this.oneData = {
            ID: goods.ID,
            BarCode: goods.BarCode,
            Name: goods.Name,
            BrandName: goods?.Category?.BrandName || '',
            ClassName: goods?.Category?.ClassName || '',
            LevelName: goods?.Category?.LevelName || '',
            BoxRule: goods.BoxRule || '',
            FactoryPrice: goods.FactoryPrice || 0.0,
            Rebate: 0.0
          }
          this.oneData.GoodsID = goods.ID
        } else {
          // this.$message({
          //   message: '未找到该条码对应的商品',
          //   type: 'warning'
          // })
          this.oneData = {
            ID: 0,
            BarCode: '',
            Name: '查无此商品',
            BrandName: '',
            ClassName: '',
            LevelName: '',
            BoxRule: '',
            FactoryPrice: 0
          }
          this.oneData.GoodsID = null
        }
      } catch (error) {
        this.$message({
          message: '搜索商品失败',
          type: 'error'
        })
      }
    },

    async confirmSubmit() {
      if (!this.oneData.GoodsID) {
        this.$message({
          message: '请先搜索并选择商品',
          type: 'warning'
        })
        return
      }

      console.log(this.oneData)

      // 准备提交数据
      const submitData = {
        GoodsID: this.oneData.GoodsID,
        Rebate: (this.oneData.Rebate || 0) / 100, // 后台存储的是[0.0, 1.0]之间的数
        ValidityStartTime: this.oneData.ValidityStartTime || null,
        ValidityEndTime: this.oneData.ValidityEndTime || null
      }

      // 验证返点是否在[0.0, 1.0]之间（已除以100）
      if (submitData.Rebate < 0.0 || submitData.Rebate > 1.0) {
        this.$message({
          message: '返点必须在[0%, 100%]之间',
          type: 'warning'
        })
        return
      }

      // 结束时间要么为空 要么不能小于开始时间
      if (submitData.ValidityEndTime && submitData.ValidityEndTime < submitData.ValidityStartTime) {
        this.$message({
          message: '结束时间不能早于开始时间',
          type: 'warning'
        })
        return
      }

      try {
        if (this.dialogType === 'new') {
          await data_api.create(submitData)
          this.$message({
            type: 'success',
            message: '返点设置保存成功'
          })
        } else {
          await data_api.update({ ...submitData, ID: this.oneData.ID })
          this.$message({
            type: 'success',
            message: '返点设置更新成功'
          })
        }
        this.dialogVisible = false
        this.getListData()
      } catch (error) {
        this.$message({
          type: 'error',
          message: this.dialogType === 'new' ? '返点设置保存失败' : '返点设置更新失败'
        })
      }
    },

    async handleDelete(scope) {
      try {
        await this.$confirm(`确认删除该返点设置？`, 'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await data_api.delete_({ ID: scope.row.ID })
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        this.getListData()
      } catch (error) {
        // 用户取消删除时也会进入catch，但不需要提示
        if (error !== 'cancel') {
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .filter-container {
    margin-bottom: 20px;
  }

  .selected-goods-info {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    div {
      margin-bottom: 5px;
      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .no-border {
    border-bottom: none !important;
  }
}
</style>
